package com.anli.Filter;

import com.alibaba.fastjson.JSONObject;
import com.anli.Utils.JwtUtils;
import com.anli.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebFilter(urlPatterns = "/depts/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String url = req.getRequestURI().toString();
        log.info("url:{}", url);

        if (url.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String jwt = req.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            log.info("token is empty");
            Result result = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(result);
            resp.getWriter().write(notLogin);
            return;
        }
        try {
//            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            log.info("jwt parse error");
            Result result = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(result);
            resp.getWriter().write(notLogin);
            return;
        }

        log.info("jwt parse success");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
